<template>
  <div class="content-wrapper" v-loading="loading">
    <div class="nav">
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/administration-assetsList' }">固定资产</el-breadcrumb-item>
        <el-breadcrumb-item>资产列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="content">
      <div class="search-bar">
        <div>
          <el-button type="primary" @click="showAddOrEditDialog(false)" v-if="isAuth('assets:hrassets:save')">新增</el-button>
          <el-button type="primary" :disabled="multipleSelection.length === 0" @click="delAssets(true)" v-if="isAuth('assets:hrassets:delete')">批量删除</el-button>
          <el-button type="primary" @click="$refs.uploadInput.click()" v-if="isAuth('assets:hrassets:save')">导入</el-button>
          <input ref="uploadInput" type="file" style="display: none;" @change="uploadFile($event)">
          <el-button type="primary" @click="exportAssets">导出模板</el-button>
        </div>
        <el-popover
          placement="bottom"
          title="筛选条件"
          width="300"
          trigger="click">
          <el-form label-width="80px" class="filter-form">
            <div style="margin-bottom: 10px">
              <el-input v-model="searchData.assetsName" clearable :placeholder="selectNameOrNumber==='1' ? '请按照资产名称查询' : '请按照资产编号查询'">
                <el-select v-model="selectNameOrNumber" slot="prepend">
                  <el-option label="资产名称" value="1"></el-option>
                  <el-option label="资产编号" value="2"></el-option>
                </el-select>
                <el-button slot="append" icon="el-icon-search" @click="getAssetsList(true)"></el-button>
              </el-input>
            </div>
            <el-form-item label="负责人">
              <div @click="selectDingUsers(searchData, 'assetsUserId','assetsUserName', 'assetsUserIdArr', 'assetsUserNameArr', 1)" class="select-btn"><span><i class="el-icon-plus"></i></span>添加</div>
              <div class="select-btn" v-for="(member, idx) in searchData.assetsUserNameArr" :key="member" style="padding: 0;">{{member}}
                <div class="del" @click="delMember(searchData, 'assetsUserId','assetsUserName', 'assetsUserIdArr', 'assetsUserNameArr', idx)">移除</div>
              </div>
            </el-form-item>
            <el-form-item label="采购时间">
              <el-row>
                <el-date-picker v-model="searchData.startTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
              </el-row>
              <el-row style="text-align: center;">至</el-row>
              <el-row>
                <el-date-picker v-model="searchData.endTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
              </el-row>
            </el-form-item>
            <el-form-item label="使用部门">
              <el-select v-model="searchData.assetsDeptId" placeholder="请选择使用部门">
                <el-option label="全部" value=""></el-option>
                <el-option v-for="item in departmentList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <div v-for="argument in argumentList" :key="argument.id" style="margin-bottom: 10px;">
              <el-form-item :label="argument.name" v-if="argument.id === '1320636393199038466' || argument.id === '1320636431732109314' || argument.id === '1320636477194170369' || argument.id === '1321021965520920577'">
                <el-select v-model="searchData.assetsType" :placeholder="'请选择'+argument.name" v-if="argument.id === '1320636393199038466'">
                  <el-option label="全部" value=""></el-option>
                  <el-option v-for="item in argument.children" :key="item.id" :label="item.name" :value="item.name"></el-option>
                </el-select>
                <el-select v-model="searchData.assetsDeptId" :placeholder="'请选择'+argument.name" v-if="argument.id === '1320636431732109314'">
                  <el-option label="全部" value=""></el-option>
                  <el-option v-for="item in argument.children" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
                <el-select v-model="searchData.assetsLocation" :placeholder="'请选择'+argument.name" v-if="argument.id === '1320636477194170369'">
                  <el-option label="全部" value=""></el-option>
                  <el-option v-for="item in argument.children" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
                <el-select v-model="searchData.assetsStatus" :placeholder="'请选择'+argument.name" v-if="argument.id === '1321021965520920577'">
                  <el-option label="全部" value=""></el-option>
                  <el-option v-for="item in argument.children" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <el-badge :is-dot="hasSearchCondition" slot="reference">
            <el-button type="primary" v-if="isAuth('assets:hrassets:list') && isAuth('assets:hrassets:info')">筛选</el-button>
          </el-badge>
        </el-popover>
      </div>
      <el-table :data="assetsList" :height="tableHeight+'px'" stripe style="width: 100%" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column :label="argumentList && argumentList[1] ? argumentList[1].name : ''" min-width="120" align="center">
          <template slot-scope="scope">
            <span v-if="argumentList && argumentList[1] && argumentList[1].id === '1320636393199038466'">{{scope.row.assetsType}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="assetsNumber" label="资产编号" min-width="100" align="center"></el-table-column>
        <el-table-column prop="assetsName" label="资产名称" min-width="150" align="center"></el-table-column>
        <el-table-column prop="assetsSpecificationModel" label="规格型号" min-width="150" align="center"></el-table-column>
        <el-table-column prop="assetsDeptName" label="使用部门" min-width="120" align="center"></el-table-column>
        <el-table-column prop="assetsUserName" label="负责人" min-width="100" align="center"></el-table-column>
        <el-table-column prop="assetsUseTime" label="使用日期" min-width="100" align="center"></el-table-column>
        <el-table-column :label="argumentList && argumentList[2] ? argumentList[2].name : ''" min-width="120" align="center">
          <template slot-scope="scope">
            <span v-if="argumentList && argumentList[2] && argumentList[2].id === '1320636477194170369'">
              <span v-for="item in argumentList[2].children" :key="item.id">
                <span v-if="scope.row.assetsLocation === item.id && argumentList[2].id === '1320636477194170369'">{{item.name}}</span>
              </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column :label="argumentList && argumentList[3] ? argumentList[3].name : ''" min-width="120" align="center">
          <template slot-scope="scope">
            <span v-if="argumentList && argumentList[3] && argumentList[3].id === '1321021965520920577'">
              <span v-for="item in argumentList[3].children" :key="item.id">
                <span v-if="scope.row.assetsStatus === item.id && argumentList[3].id === '1321021965520920577'">{{item.name}}</span>
              </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="assetsPurchaseTime" label="采购时间" min-width="100" align="center"></el-table-column>
        <el-table-column prop="assetsPurchaseAmount" label="采购金额" min-width="100" align="center"></el-table-column>
        <el-table-column prop="assetsManufacturer" label="生产厂商" min-width="100" align="center"></el-table-column>
        <el-table-column prop="assetsIsEncryption" label="是否加密" min-width="100" align="center">
          <template slot-scope="scope">{{scope.row.assetsIsEncryption ? '是' : '否'}}</template>
        </el-table-column>
        <el-table-column prop="assetsHasLabel" label="是否贴标签" min-width="100" align="center">
          <template slot-scope="scope">{{scope.row.assetsHasLabel ? '是' : '否'}}</template>
        </el-table-column>
        <el-table-column :label="argumentList && argumentList[0] ? argumentList[0].name : ''" min-width="120" align="center">
          <template slot-scope="scope">
            <span v-if="argumentList && argumentList[0] && argumentList[0].id === '1320636343882412034'">
              <span v-for="item in argumentList[0].children" :key="item.id">
                <span v-if="scope.row.assetsLoss === item.id && argumentList[0].id === '1320636343882412034'">{{item.name}}</span>
              </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="assetsServiceLife" label="使用年限" min-width="100" align="center"></el-table-column>
        <el-table-column prop="assetsEncryptionDescription" label="加密情况" min-width="100" align="center"></el-table-column>
        <el-table-column prop="assetsEncryptionCode" label="绿盾加密编码" min-width="120" align="center"></el-table-column>
        <el-table-column prop="assetsRemark" label="备注" min-width="100" align="center"></el-table-column>
        <el-table-column label="操作" min-width="100" align="center">
          <template slot-scope="scope">
            <el-button type="text" style="padding: 0;" @click="showAddOrEditDialog(scope.row)" v-if="isAuth('assets:hrassets:update')">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageConfig.pageIndex"
          :page-sizes="[10, 15, 20, 50]"
          :page-size="pageConfig.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageConfig.totalCount">
        </el-pagination>
      </div>
    </div>
    <el-dialog :title="!form.id ? '新增资产' : '编辑资产'" :visible.sync="dialogVisible" :close-on-click-modal="false" width="800px">
      <div>
        <el-form ref="form" :model="form" label-width="100px" label-position="right">
          <el-form-item label="资产编号" prop="assetsNumber" :rules="[{ required: true, message: '请输入资产编号', trigger: 'blur' }]">
            <el-input v-model="form.assetsNumber" placeholder="请输入资产编号"></el-input>
          </el-form-item>
          <el-form-item label="资产名称" prop="assetsName" :rules="[{ required: true, message: '请输入资产名称', trigger: 'blur' }]">
            <el-input v-model="form.assetsName" placeholder="请输入资产名称"></el-input>
          </el-form-item>
          <el-form-item label="规格型号">
            <el-input v-model="form.assetsSpecificationModel" placeholder="请输入规格型号"></el-input>
          </el-form-item>
          <el-form-item label="使用部门">
            <el-select ref="assetsDeptIdSelect" v-model="form.assetsDeptId" placeholder="请选择使用部门" style="width: 100%;">
              <el-option v-for="item in departmentList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="argument.name" v-for="argument in argumentList" :key="argument.id">
            <el-select clearable v-model="form.assetsLoss" :placeholder="'请选择'+argument.name" v-if="argument.id === '1320636343882412034'" style="width: 100%;">
              <el-option v-for="item in argument.children" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select clearable v-model="form.assetsType" :placeholder="'请选择'+argument.name" v-if="argument.id === '1320636393199038466'" style="width: 100%;">
              <el-option v-for="item in argument.children" :key="item.id" :label="item.name" :value="item.name"></el-option>
            </el-select>
            <el-select clearable v-model="form.assetsLocation" :placeholder="'请选择'+argument.name" v-if="argument.id === '1320636477194170369'" style="width: 100%;">
              <el-option v-for="item in argument.children" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="form.assetsStatus" :placeholder="'请选择'+argument.name" v-if="argument.id === '1321021965520920577'" style="width: 100%;">
              <el-option v-for="item in argument.children" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="使用年限">
            <el-input v-model="form.assetsServiceLife" placeholder="请输入使用年限"></el-input>
          </el-form-item>
          <el-form-item label="负责人">
            <div @click="selectDingUsers(form, 'assetsUserId','assetsUserName','assetsUserIdArr', 'assetsUserNameArr', 1)" class="select-btn"><span><i class="el-icon-plus"></i></span>添加</div>
            <div class="select-btn" v-for="(member, idx) in form.assetsUserNameArr" :key="member" style="padding: 0;">{{member}}
              <div class="del" @click="delMember(form, 'assetsUserId','assetsUserName', 'assetsUserIdArr', 'assetsUserNameArr', idx)">移除</div>
            </div>
          </el-form-item>
          <el-form-item label="使用日期">
            <el-date-picker v-model="form.assetsUseTime" type="date" placeholder="请选择使用日期" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
          <el-form-item label="采购时间">
            <el-date-picker v-model="form.assetsPurchaseTime" type="date" placeholder="请选择采购时间" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
          <el-form-item label="采购金额">
            <el-input v-model="form.assetsPurchaseAmount" placeholder="请输入采购金额" type="number" min="0" @wheel.native.prevent="stopScrollFun($event)"></el-input>
          </el-form-item>
          <el-form-item label="生产厂商">
            <el-input v-model="form.assetsManufacturer" placeholder="请输入生产厂商"></el-input>
          </el-form-item>
          <el-form-item label="是否加密">
            <el-switch v-model="form.assetsIsEncryption"></el-switch>
          </el-form-item>
          <el-form-item label="是否贴标签">
            <el-switch v-model="form.assetsHasLabel"></el-switch>
          </el-form-item>
          <el-form-item label="加密情况">
            <el-input v-model="form.assetsEncryptionDescription" placeholder="请输入加密情况"></el-input>
          </el-form-item>
          <el-form-item label="绿盾加密编码">
            <el-input v-model="form.assetsEncryptionCode" placeholder="请输入绿盾加密编码"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" rows="3" v-model="form.assetsRemark" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" style="display: flex; justify-content: space-between;">
          <div><el-button size="mini" type="danger" v-if="form.id && isAuth('assets:hrassets:delete')" @click="delAssets(false)">删除</el-button></div>
          <div>
            <el-button @click="dialogVisible = false" size="mini">取消</el-button>
            <el-button type="primary" size="mini" @click="submitForm">保存</el-button>
          </div>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dingMixin from  '@/mixins/ding'
import formUtil from '@/utils/formUtil'
export default {
  data () {
    return {
      selectNameOrNumber: '1',
      searchDataInit: {},
      searchData: {
        assetsName: '',
        assetsType: '',
        assetsUserId: '',
        assetsUserIdArr: [],
        assetsUserName: '',
        assetsUserNameArr: [],
        assetsDeptId: '',
        assetsLocation: '',
        startTime: null,
        endTime: null,
        assetsStatus: '',
      },
      assetsList: [],
      tableHeight: '',
      pageConfig: {
        pageIndex: 1,
        pageSize: 15,
        totalCount: 0,
      },
      argumentList: [],
      form: {
        assetsNumber: '',
        assetsName: '',
        assetsType: '',
        assetsUserId: '',
        assetsUserIdArr: [],
        assetsUserName: '',
        assetsUserNameArr: [],
        assetsDeptId: '',
        assetsDeptName: '',
        assetsLoss: '',
        assetsLocation: '',
        assetsPurchaseTime: '',
        assetsServiceLife: '',
        assetsRemark: '',
        assetsStatus: '',
        assetsEncryptionCode: '',
        assetsEncryptionDescription: '',
        assetsHasLabel: false,
        assetsIsEncryption: false,
        assetsManufacturer: '',
        assetsPurchaseAmount: '',
        assetsSpecificationModel: '',
        assetsUseTime: ''
      },
      dialogVisible: false,
      multipleSelection: [],
      departmentList: [],
      loading: false,
    };
  },
  mixins: [dingMixin],
  watch: {
    searchData: {
      handler() {
        this.getAssetsList(true)
      },
      deep: true
    }
  },
  computed: {
    hasSearchCondition() {
      return JSON.stringify(this.searchData) !== this.searchDataInit
    },
  },
  mounted () {
    this.tableHeight = document.documentElement['clientHeight'] - 150
    window.onresize = () => {
      this.tableHeight = document.documentElement['clientHeight'] - 150
    }
    this.searchDataInit = JSON.stringify(this.searchData)
    this.getDictList()
    this.getAssetsList(true)
    this.getDepartmentList()
  },
  methods: {
    //禁止滚动
    stopScrollFun(evt) {
      evt = evt || window.event;
      if(evt.preventDefault) {
        evt.preventDefault();
        evt.stopPropagation();
      } else {
        evt.cancelBubble=true;
        evt.returnValue = false;
      }
      return false;
    },
    async getDepartmentList() {
      let dept = await this.$httpN.postB('sys/dept/listAll')
      let firstArr = dept.filter(item => {
          item.idsArr = [item.id]
          return item.pid === '1'
      } )
      this.departmentList = firstArr
    },
    async getDictList() {
      let {list} = await this.$httpN.postB('hr/dict/list', { pid: '1320636169097375745', limit: 999 })
      if(typeof list === 'undefined' || typeof list === 'boolean') return
      list.forEach(item => {
        item.children = [];
        this.getSubDictList(item)
      })
      this.argumentList = list.filter( item => item.id === '1320636343882412034' || item.id === '1320636393199038466' || item.id === '1320636431732109314' || item.id === '1320636477194170369' || item.id === '1321021965520920577');
    },
    async getSubDictList(item) {
      let {list} = await this.$httpN.postB('hr/dict/list', { pid: item.id, limit: 999 })
      item.children.push(...list)
    },
    async getAssetsList(init) {
      if(init) this.pageConfig.pageIndex = 1
      let {list, totalCount} = await this.$httpN.postB('hr/assets/list', {
        page: this.pageConfig.pageIndex,
        limit: this.pageConfig.pageSize,
        assetsNumber: this.selectNameOrNumber === '2' ? this.searchData.assetsName : '',
        assetsName: this.selectNameOrNumber === '1' ? this.searchData.assetsName : '',
        assetsType: this.searchData.assetsType,
        assetsUserId: this.searchData.assetsUserId,
        assetsDeptId: this.searchData.assetsDeptId,
        assetsLocation: this.searchData.assetsLocation,
        startTime: this.searchData.startTime,
        endTime: this.searchData.endTime,
        assetsStatus: this.searchData.assetsStatus
      })
      this.assetsList = list
      if(init) this.pageConfig.totalCount = totalCount
    },
    handleSizeChange(val) {
      this.pageConfig.pageSize = val;
      this.getAssetsList(true)
    },
    handleCurrentChange(val) {
      this.pageConfig.pageIndex = val;
      this.getAssetsList()
    },
    delMember(form, id, name, idArr, nameArr, idx) {
      form[nameArr].splice(idx,1); 
      form[idArr].splice(idx,1); 
      form[name] =form[nameArr].join(',')
      form[id] = form[idArr].join(',')
    },
    selectDingUsers(form, id, name, idArr, nameArr, num){
      this.complexPicker(num, [], form[idArr]).then((data)=>{
        form[idArr] = data.map(item => item.emplId);
        form[nameArr] = data.map(item => item.name)
        form[name] = form[nameArr].join(',');
        form[id] = form[idArr].join(',')
      })
    },
    showAddOrEditDialog(item) {
      formUtil.resetData(this.form);
      if(this.$refs.form) this.$refs.form.clearValidate();
      if(item) {
        item.assetsUserIdArr = item.assetsUserId ? item.assetsUserId.split(',') : []
        item.assetsUserNameArr = item.assetsUserName ? item.assetsUserName.split(',') : []
        this.form = JSON.parse(JSON.stringify(item))
      }
      this.dialogVisible = true;
    },
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.form.assetsDeptName = this.form.assetsDeptId ? this.$refs.assetsDeptIdSelect.selectedLabel : '';
          if(!await this.$httpN.postB(!this.form.id ? "hr/assets/save" : "hr/assets/update", this.form)) return;
          formUtil.submitSuccess('保存成功');
          this.dialogVisible = false;
          this.getAssetsList(true);
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delAssets(type) {
      let ids = type ? this.multipleSelection.map(item => item.id) : [this.form.id]
      formUtil.submitConfirm('请问您是否确认删除该资产', async ()=> {
        if(!await this.$httpN.postB('hr/assets/delete', ids, false)) return;
        formUtil.submitSuccess('删除成功');
        this.dialogVisible = false;
        this.getAssetsList(true);
      })
    },
    uploadFile(e) {
      this.loading = true
      let file = e.target.files[0];
      var formData = new FormData();
      formData.append("file", file);
      formData.append("name", 'file');
      this.$httpN.upload('hr/assets/fileUpload', formData).then((res) => {
        this.loading = false
        if(res.status === 200 && res.data.code === 0) {
          formUtil.submitSuccess('上传成功')
          if(res.data.data.jumpData && res.data.data.jumpData.indexOf('[') !== -1) this.$message.warning('资产编号重复的数据已跳过导入')
          this.getAssetsList(true);
        }else{
          this.$message.error('上传文件出错,请重试')
        }
      })
      e.target.value = '';
    },
    async exportAssets() {
      let fileData = await this.$httpN.get('hr/assets/templateExport', {}, 'blob');
      this.downFile(fileData, '资产模板.xls');
    },
    downFile(blob, fileName) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
      }
    },
  }
}
</script>

<style lang='scss' scoped>
.content-wrapper {
  height: 100vh;
  .nav {
    display: flex;
    height: 50px;
    line-height: 50px;
    padding: 0 20px;
    justify-content: space-between;
    border-bottom: 1px solid #DCDFE6;
    .el-breadcrumb {
      display: flex;
      align-items: center;
      .el-breadcrumb__item {
        float: none;
      }
    }
  }
  .content {
    padding: 0 20px;
    height: calc(100vh - 50px);
    overflow: auto;
    .search-bar {
      height: 50px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .page {
      height: 50px;
      display: flex;
      align-items: center;
      flex-direction: row-reverse;
    }
  }
}
.filter-form {
  max-height: 424px;
  overflow: auto;
  .el-form-item {
    margin-bottom: 10px;
    &:last-child {
      margin-bottom: 0;
    }
  }
}
.select-btn{
  float:left;
  font-weight: normal;
  margin-right: 5px;
  margin-bottom: 10px;
  width: 80px;
  height: 28px;
  border-radius: 30px;
  background: #FAFAFA;
  border: 1px solid #ECECEC;
  position: relative;
  padding-left: 21px;
  line-height: 28px;
  color: #7982A7;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
  span{
    position: absolute;
    top: 1px;
    left: 1px;
    display:block;
    height: 24px;
    width: 24px;
    background: #CACACA;
    color: white;
    border-radius: 50%;
    text-align: center;
    line-height: 24px;
    img{
      width: 24px;
      height: 24px;
      border-radius: 50%;
    }
  }
  .del{
    position: absolute;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 30px;
    color: white;
    text-align: center;
    background:rgba(130, 130, 130, 0.9);
    display: none;
  }
  &:hover{
    .del{
      display: block;
    }
  }
}
</style>